from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import db, Lyrics, Storyboard
from app.services.lyrics_service import DeepseekService, StableDiffusionService
from app.services.ServerApi import build_prompt, query_deepseek, extract_bilingual_scenes, generate_image, modify_image
import os


lyrics_api = Blueprint('lyrics_api', __name__, url_prefix='/lyrics')

# @lyrics_api.route('/', methods=['POST'])
# @jwt_required()
# def create_lyrics():
#     """创建新歌词"""
#     data = request.json
    
#     if not data or 'title' not in data or 'content' not in data:
#         return jsonify({'error': '缺少必要参数'}), 400
        
#     lyrics = Lyrics(
#         title=data['title'],
#         content=data['content'],
#         user_id=get_jwt_identity()
#     )
#     db.session.add(lyrics)
#     db.session.commit()
    
#     return jsonify({
#         'message': '歌词保存成功',
#         'lyrics': lyrics.to_dict()
#     }), 201

# # 查看特定歌词
# @lyrics_api.route('/<int:lyrics_id>', methods=['GET'])
# @jwt_required()
# def get_lyrics(lyrics_id):
#     """获取歌词详情"""
#     lyrics = Lyrics.query.get_or_404(lyrics_id)
    
#     # 检查权限
#     if lyrics.user_id != get_jwt_identity():
#         return jsonify({'error': '您无权访问此歌词'}), 403
        
#     # 获取该歌词的所有分镜
#     storyboards = [storyboard.to_dict() for storyboard in lyrics.storyboards.all()]
        
#     return jsonify({
#         'lyrics': lyrics.to_dict(),
#         'storyboards': storyboards
#     }), 200

# # 获取用户所有歌词
# @lyrics_api.route('/', methods=['GET'])
# @jwt_required()
# def get_all_lyrics():
#     """列出用户的所有歌词"""
#     user_id = get_jwt_identity()
#     lyrics_list = Lyrics.query.filter_by(user_id=user_id).all()
#     return jsonify({
#         'lyrics': [lyrics.to_dict() for lyrics in lyrics_list]
#     }), 200

# # 获取歌词对应的分镜
# @lyrics_api.route('/<int:lyrics_id>/storyboards', methods=['GET'])
# @jwt_required()
# def get_storyboards(lyrics_id):
#     """获取特定歌词的所有分镜"""
#     lyrics = Lyrics.query.get_or_404(lyrics_id)
    
#     # 检查权限
#     if lyrics.user_id != get_jwt_identity():
#         return jsonify({'error': '您无权访问此歌词的分镜'}), 403
        
#     storyboards = [storyboard.to_dict() for storyboard in lyrics.storyboards.all()]
    
#     return jsonify({
#         'storyboards': storyboards
#     }), 200

# @lyrics_api.route('/storyboard/<int:storyboard_id>/img2img', methods=['POST'])
# @jwt_required()
# def storyboard_img2img(storyboard_id):
#     """基于现有分镜图片创建新的变体"""
#     # 获取分镜和权限检查
#     storyboard = Storyboard.query.get_or_404(storyboard_id)
#     lyrics = Lyrics.query.get(storyboard.lyrics_id)
    
#     # 检查权限
#     if lyrics.user_id != get_jwt_identity():
#         return jsonify({'error': '您无权修改此分镜'}), 403
    
#     data = request.json
#     if not data or 'prompt' not in data:
#         return jsonify({'error': '缺少必要的提示词'}), 400
    
#     # 获取请求参数
#     prompt = data.get('prompt')
#     negative_prompt = data.get('negative_prompt')
#     strength = float(data.get('strength', 0.7))  # 控制变化的强度
    
#     try:
#         # 获取原始图片的完整路径
#         image_path = os.path.join(current_app.static_folder, storyboard.image_path)
        
#         # 创建服务实例
#         sd_service = StableDiffusionService(os.environ.get("STABILITY_API_KEY"))
        
#         # 调用图生图功能
#         new_image_path = sd_service.img2img(
#             image_source=image_path,
#             prompt=prompt,
#             negative_prompt=negative_prompt,
#             strength=strength
#         )
        
#         # 更新分镜记录或创建新记录
#         if data.get('create_new', False):
#             # 创建新分镜
#             new_storyboard = Storyboard(
#                 name=f"{storyboard.name} - 变体",
#                 lyrics_segment=storyboard.lyrics_segment,
#                 description=prompt,
#                 image_path=new_image_path,
#                 lyrics_id=storyboard.lyrics_id,
#                 style=storyboard.style
#             )
#             db.session.add(new_storyboard)
#             db.session.commit()
#             return jsonify({
#                 'message': '已创建新的分镜变体',
#                 'storyboard': new_storyboard.to_dict()
#             }), 201
#         else:
#             # 更新现有分镜
#             storyboard.image_path = new_image_path
#             storyboard.description = f"{storyboard.description} - {prompt}"
#             db.session.commit()
#             return jsonify({
#                 'message': '分镜已更新',
#                 'storyboard': storyboard.to_dict()
#             }), 200
    
#     except Exception as e:
#         current_app.logger.error(f"图生图处理失败: {str(e)}")
#         return jsonify({'error': f'图生图处理失败: {str(e)}'}), 500
    
@lyrics_api.route('/generate', methods=['POST'])
@jwt_required()
def generate_storyboards():
    """生成图片分镜，返回 ID/URL/标题 列表"""
    data = request.get_json(silent=True)
    if not data or 'lyrics' not in data:
        return jsonify({"code": 400, "message": "请提供歌词列表", "data": []}), 400

    lyrics = data['lyrics']
    keywords = ', '.join(data.get('keywords', []))
    image_pathes = data['images']
    try:
        # 构建提示并调用 DeepSeek
        prompt = build_prompt(lyrics=lyrics, style=keywords)
        response_text = query_deepseek(prompt)
        scenes = extract_bilingual_scenes(response_text)

        result = []
        if image_pathes != None:
             for index, scene in enumerate(scenes):
                path = generate_image(scene.get('English'))
        
                result.append({
                    "id": index + 1,
                    "url": path,
                    "title": scene.get("title", f"Scene {index + 1}"),
                    "description": scene.get("Chinese")
                })
        else:
            for index, scene in enumerate(scenes):
                path = modify_image(scene.get('Chinese'))
                result.append({
                    "id": index + 1,
                    "url": path,
                    "title": scene.get("title", f"Scene {index + 1}"),
                    "description": scene.get("Chinese")
                })
        
        return jsonify({
            "code" : 200,
            "message" : "成功生成分镜",
            "data" : result
        })
    except Exception as e:
        current_app.logger.error(f"分镜生成失败: {e}")
        return jsonify({
            "code": 500,
            "message": f"生成失败: {e}",
            "data": []
        })

    # data = request.json or {}
    # if 'lyrics' not in data or not isinstance(data['lyrics'], list) or not data['lyrics']:
    #     return jsonify({"code": 400, "message": "请提供歌词列表", "data": []}), 400

    # # 1. 准备歌词文本
    # full_lyrics = "\n".join(data['lyrics'])
    # try:
    #     # 2. 调用 ServerApi 构建提示并获取分镜文本
    #     prompt = build_prompt(full_lyrics)
    #     response_text = query_deepseek(prompt)
    #     scenes = extract_bilingual_scenes(response_text)

    #     # 3. 为每个 scene 生成图片，并组装返回 payload
    #     payload = []
    #     for idx, scene in enumerate(scenes, start=1):
    #         # 生成图片，保存为 generated_image_<scene_index>_0.png
    #         generate_image(
    #             positive_prompt=scene.get("english"),
    #             negative_prompt=None,
    #             num_images=1,
    #             scene_index=idx-1
    #         )
    #         # 图片文件名和访问 URL
    #         filename = f"generated_image_{idx-1}_0.png"
    #         file_url = url_for('static', filename=filename, _external=False)

    #         payload.append({
    #             "id": idx,
    #             "url": file_url,
    #             "title": scene.get("title", f"Scene {idx}"),
    #             "description": scene.get("chinese")
    #         })

    #     return jsonify({
    #         "code": 200,
    #         "message": "生成成功",
    #         "data": payload
    #     })

    # except Exception as e:
    #     current_app.logger.error(f"歌词生成失败: {e}")
    #     return jsonify({
    #         "code": 500,
    #         "message": f"生成失败: {e}",
    #         "data": []
    #     })